import os
from typing import Dict, List, Any
import json

class DocumentBuilder:
    def __init__(self, previous_builder=None):
        if previous_builder:
            # 继承上一个构建器的内容
            import copy
            self.sections = copy.deepcopy(previous_builder.sections)
        else:
            # 初始化新的空文档
            self.sections = {
                "overview": "",
                "parameters": [],
                "classes": {},  # 使用字典存储类及其方法
                "functions": [],
                "diagrams": [],
                "call_hierarchy": ""
            }
        self.section_titles = {
            "overview": "概述",
            "classes": "类详细说明",
            "functions": "函数详细说明",
            "diagrams": "程序框图",
            "call_hierarchy": "调用层次结构"
        }

        
    def set_overview_to_submodule(self, overview_text: str):
        """设置文档概述部分"""
        if not self.sections["overview"]:
            self.sections["overview"] = overview_text
        else:
            self.sections["overview"] += "\n\n" + overview_text

    #parameter是给谁的？       
    def add_parameter(self, name: str, description: str, default_value: str = None, data_type: str = None):
        """添加参数说明"""
        self.sections["parameters"].append({
            "name": name,
            "description": description,
            "default_value": default_value,
            "data_type": data_type
        })
        
    def add_class_to_submodule(self, name: str, description: str, methods: List[Dict[str, Any]] = None, properties: List[Dict[str, Any]] = None):
        """添加类说明"""
        self.sections["classes"][name] = {
            "description": description,
            "methods": methods or [],
            "properties": properties or []
        }
        
    def add_method_to_class(self, class_name: str, method_name: str, description: str, 
                           parameters: List[Dict[str, str]] = None, return_value: Dict[str, str] = None):
        """添加方法到现有类"""
        if class_name not in self.sections["classes"]:
            self.sections["classes"][class_name] = {"description": "", "methods": [], "properties": []}
            
        self.sections["classes"][class_name]["methods"].append({
            "name": method_name,
            "description": description,
            "parameters": parameters or [],
            "return_value": return_value or {}
        })
  
        
    def add_function_to_submodule(self, name: str, description: str, parameters: List[Dict[str, Any]] = None, return_value: Dict[str, Any] = None):
        """添加函数说明"""
        self.sections["functions"].append({
            "name": name,
            "description": description,
            "parameters": parameters or [],
            "return_value": return_value or {}
        })

    #        
    def add_diagram(self, diagram_type: str, diagram_content: str):
        """添加图表"""
        self.sections["diagrams"].append({
            "type": diagram_type,
            "content": diagram_content
        })
        
    def set_call_hierarchy(self, hierarchy_text: str):
        """设置调用层次结构"""
        self.sections["call_hierarchy"] = hierarchy_text
        
    def merge_sections(self, iteration=1) -> str:
        """合并所有部分生成完整文档，支持标题递增"""
        doc = []
        
        # 添加文档标题
        if iteration > 1:
            doc.append(f"# 代码文档 (迭代 {iteration})\n\n")
        else:
            doc.append("# 代码文档\n\n")
            
        # 添加概述
        if self.sections["overview"]:
            doc.append(f"## {self.section_titles['overview']}\n\n")
            doc.append(self.sections["overview"])
            doc.append("\n\n")
            
        # 添加参数表格
        if self.sections["parameters"]:
            doc.append("## 关键参数\n\n")
            doc.append("| 参数名 | 数据类型 | 默认值 | 说明 |\n")
            doc.append("|--------|----------|--------|------|\n")
            
            for param in self.sections["parameters"]:
                doc.append(f"| {param['name']} | {param['data_type'] or '-'} | {param['default_value'] or '-'} | {param['description']} |\n")
            
            doc.append("\n")
            
        # 添加类说明
        if self.sections["classes"]:
            # 为后续迭代添加递增标题编号
            if iteration > 1:
                doc.append(f"## {self.section_titles['classes']} {iteration}\n\n")
            else:
                doc.append(f"## {self.section_titles['classes']}\n\n")
            
            for class_name, class_info in self.sections["classes"].items():
                doc.append(f"### {class_name}\n\n")
                doc.append(f"{class_info['description']}\n\n")
                
                if class_info["properties"]:
                    doc.append("#### 属性\n\n")
                    doc.append("| 属性名 | 类型 | 说明 |\n")
                    doc.append("|--------|------|------|\n")
                    
                    for prop in class_info["properties"]:
                        doc.append(f"| {prop['name']} | {prop['data_type'] or '-'} | {prop['description']} |\n")
                    
                    doc.append("\n")
                
                if class_info["methods"]:
                    doc.append("#### 方法\n\n")
                    
                    for method in class_info["methods"]:
                        doc.append(f"##### `{method['name']}`\n\n")
                        doc.append(f"{method['description']}\n\n")
                        
                        if method.get("parameters"):
                            doc.append("参数:\n\n")
                            for param in method["parameters"]:
                                doc.append(f"- `{param['name']}` ({param.get('data_type', '-')}): {param['description']}\n")
                            doc.append("\n")
                        
                        if method.get("return_value") and method["return_value"].get("description"):
                            doc.append(f"返回值: {method['return_value'].get('data_type', '-')} - {method['return_value']['description']}\n\n")
        
        # 添加函数说明 
        if self.sections["functions"]:
            # 为后续迭代添加递增标题编号
            if iteration > 1:
                doc.append(f"## {self.section_titles['functions']} {iteration}\n\n")
            else:
                doc.append(f"## {self.section_titles['functions']}\n\n")
            
            for func in self.sections["functions"]:
                doc.append(f"### `{func['name']}`\n\n")
                doc.append(f"{func['description']}\n\n")
                
                if func["parameters"]:
                    doc.append("参数:\n\n")
                    for param in func["parameters"]:
                        doc.append(f"- `{param['name']}` ({param.get('data_type', '-')}): {param['description']}\n")
                    doc.append("\n")
                
                if func.get("return_value") and func["return_value"].get("description"):
                    doc.append(f"返回值: {func['return_value'].get('data_type', '-')} - {func['return_value']['description']}\n\n")
        
        # 添加调用层次
        if self.sections["call_hierarchy"]:
            doc.append("## 调用层次结构\n\n")
            doc.append(self.sections["call_hierarchy"])
            doc.append("\n\n")
            
        # 添加图表
        if self.sections["diagrams"]:
            doc.append("## 程序框图\n\n")
            
            for diagram in self.sections["diagrams"]:
                doc.append(f"### {diagram['type']}\n\n")
                doc.append(f"{diagram['content']}\n\n")
        
        return "".join(doc)
    
    def to_json(self):
        """将文档结构转换为JSON格式"""
        return json.dumps(self.sections, indent=2)
